<?php

namespace App\Http\Controllers\Vue;

use App\Http\Controllers\Controller;
use Jinxing\Admin\Repositories\Article\ArticlesRepository;

/**
 * Class ArticlesController 文章列表
 *
 * @package App\Http\Controllers\Vue
 */
class ArticlesController extends Controller
{
    /**
     * @var ArticlesRepository
     */
    private $articlesRepository;

    public function __construct(ArticlesRepository $articlesRepository)
    {
        $this->articlesRepository = $articlesRepository;
    }

    public function index()
    {
        return $this->success($this->articlesRepository->filterFindAll($this->getCondition(), [
            '*',
            'typeInfo' => ['type_id', 'name'],
        ]));
    }

    /**
     * 查询详情信息
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function show()
    {
        // 没有数据
        if (!$article = $this->articlesRepository->find(request()->get('id'))) {
            return $this->error();
        }

        // next
        $next = $this->articlesRepository->find([
            'id:gt' => $article['id'],
            'order' => 'id asc',
        ], ['id', 'title']);


        // prev
        $prev = $this->articlesRepository->find([
            'id:lt' => $article['id'],
            'order' => 'id desc',
        ], ['id', 'title']);

        return $this->success(compact('article', 'next', 'prev'));
    }

    /**
     * 查询列表信息
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function list()
    {
        $paginate = $this->articlesRepository->filterPaginate($this->getCondition(), [
            '*',
            'typeInfo' => ['type_id', 'name'],
        ]);

        return $this->success([
            'items' => $paginate->items(),
            'total' => $paginate->total(),
        ]);
    }

    /**
     * 获取查询条件信息
     *
     * @return array
     */
    private function getCondition()
    {
        return array_merge([
            'status' => 1,
            'order'  => request()->input('orderBy', 'sort asc,id desc'),
        ], request()->except('orderBy'));
    }
}
